import {SM4} from "gm-crypto";
import * as CryptoJS from 'crypto-js';
// 初始化SM4加密对象
let iv = import.meta.env.VITE_SM4_IV;

// 配置SM4加密对象
function encryptConfig(mode:string){
    if(mode === "ECB"){
       return {
         inputEncoding: 'utf8',
         outputEncoding: 'base64'
        };
    }
    //CBC模式需要配置iv向量
    return {
        mode: SM4.constants.CBC,
        iv:iv,
        inputEncoding: 'utf8',
        outputEncoding: 'base64'
        };
}
// 配置SM4加密对象
function decryptConfig(mode:string){
    if(mode === "ECB"){
       return {
         inputEncoding: 'base64',
         outputEncoding: 'utf8'
        };
    }
    //CBC模式需要配置iv向量
    return {
        mode: SM4.constants.CBC,
        iv:iv,
        inputEncoding: 'base64',
        outputEncoding: 'utf8'
        };
}
//加密数据
export function encrypt(data: string, key: string,mode:string = "CBC") {
    let sm4Config = encryptConfig(mode);
    return SM4.encrypt(data,key,sm4Config);
}
//解密数据
export function decrypt(data: string, key: string,mode:string = "CBC") {
    let sm4Config = decryptConfig(mode);
    return SM4.decrypt(data,key,sm4Config);
}
//生成指定位数随机密钥，国密32位密钥，注意一个字符等于2个字节
export function generateKey(byteLen: number = 16) {
    const validLengths= [16, 24, 32];
    if(!validLengths.includes(byteLen) ){
        return new Error("Invalid key length. Must be 16, 24 or 32 bytes");
    }
    //生成随机wordArray并转换成16进制字符串
    let wordArray = CryptoJS.lib.WordArray.random(byteLen);
    //转换成16进制字符串
    return CryptoJS.enc.Hex.stringify(wordArray);
}